using aichat.Data;
using aichat.Entities;
using Microsoft.EntityFrameworkCore;

namespace aichat.Services
{
    public class ChatService : IChatService
    {
        private readonly ApplicationDbContext _context;
        private readonly IUserService _userService;
        private readonly IAiApiService _aiApiService;

        public ChatService(ApplicationDbContext context, IUserService userService, IAiApiService aiApiService)
        {
            _context = context;
            _userService = userService;
            _aiApiService = aiApiService;
        }

        public async Task<ChatMessage> SendMessageAsync(int userId, string message, string aiModel)
        {
            // 检查用户是否可以聊天
            if (!await _userService.CanUserChatAsync(userId))
            {
                throw new InvalidOperationException("用户已达到今日聊天限制或不是VIP用户");
            }

            // 检查AI模型是否可用
            var availableModels = await GetAvailableAiModelsAsync(userId);
            var selectedModel = availableModels.FirstOrDefault(m => m.Name == aiModel);
            if (selectedModel == null)
            {
                throw new InvalidOperationException("选择的AI模型不可用");
            }

            // 生成AI响应
            var aiResponse = await GetTypingResponseAsync(message, aiModel, null);

            // 创建聊天记录
            var chatMessage = new ChatMessage
            {
                UserId = userId,
                UserMessage = message,
                AiResponse = aiResponse,
                AiModel = aiModel,
                TokensUsed = EstimateTokens(message + aiResponse),
                IsSuccessful = true
            };

            _context.ChatMessages.Add(chatMessage);
            await _context.SaveChangesAsync();

            // 增加用户聊天次数
            await _userService.IncrementChatCountAsync(userId);

            return chatMessage;
        }

        public async Task<List<ChatMessage>> GetUserChatHistoryAsync(int userId, int page = 1, int pageSize = 20)
        {
            return await _context.ChatMessages
                .Where(c => c.UserId == userId)
                .OrderBy(c => c.CreatedAt)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
        }

        public async Task<bool> DeleteChatMessageAsync(int messageId, int userId)
        {
            var message = await _context.ChatMessages
                .FirstOrDefaultAsync(c => c.Id == messageId && c.UserId == userId);
            
            if (message != null)
            {
                _context.ChatMessages.Remove(message);
                await _context.SaveChangesAsync();
                return true;
            }
            return false;
        }

        public async Task<List<AiModel>> GetAvailableAiModelsAsync(int userId)
        {
            var isVip = await _userService.IsVipUserAsync(userId);
            
            var allModels = await _context.AiModels.ToListAsync();
          
            var availableModels = await _context.AiModels
                .Where(m => m.IsActive && (!m.IsVipOnly || isVip))
                .OrderBy(m => m.SortOrder)
                .ToListAsync();
                
            foreach (var model in availableModels)
            {
                System.Diagnostics.Debug.WriteLine($"可用模型: {model.Name} - {model.DisplayName} - 活跃:{model.IsActive} - VIP:{model.IsVipOnly}");
            }
            
            return availableModels;
        }

        public async Task<string> GetTypingResponseAsync(string message, string aiModel, IProgress<string>? progress)
        {
            try
            {
                // 检查API是否配置
                if (!_aiApiService.IsConfigured())
                {
                    throw new InvalidOperationException("AI API未配置，请设置相应的API密钥");
                }

                // 调用真实的AI API
                return await _aiApiService.GetStreamingResponseAsync(message, aiModel, progress);
            }
            catch (Exception ex)
            {
                // 如果API调用失败，返回错误信息
                var errorMessage = $"AI服务暂时不可用: {ex.Message}";
                progress?.Report(errorMessage);
                return errorMessage;
            }
        }

        private int EstimateTokens(string text)
        {
            // 简单的token估算：大约4个字符=1个token
            return Math.Max(1, text.Length / 4);
        }

        public async Task<bool> SaveChatMessageAsync(ChatMessage chatMessage)
        {
            try
            {
                _context.ChatMessages.Add(chatMessage);
                await _context.SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
} 